package atguigu.demo3

/**
  * Created by lzd on 2018/10/26.
  */
object demo2_1 {
  def main(args: Array[String]): Unit = {
    println(abs(1), abs(-2))

    println(fac(2))

    println(returnfun(10))

    println(fun1("hello"))

    println(fun1("hello", "<<<", ">>>"))

    println(fun2(1, 2, 3))

    //_* 告诉编译器1-5，当做参数处理
    println(fun2(1 to 5: _*))

    println(fun3(1 to 5: _*))

    box("Fred")

    box1("Wilma")
  }

  //定义函数返回类型自行推断
  def abs(x: Double) = if (x > 0) x else -x

  // {} 最后一个表达式为返回值
  def fac(n: Int) = {
    var r = 1
    for (i <- 1 to n) r = r * i
    r
  }

  //递归函数必须指定返回值类型
  def returnfun(n: Int): Int = {
    if (n <= 0) 1 else n * returnfun(n - 1)
  }

  //设置默认参数
  def fun1(a: String, b: String = "[", c: String = "]") = {
    b + a + c
  }

  //变长参数
  def fun2(args: Int*) = {
    var res = 0;
    for (arg <- args) {
      res += arg
    }
    res
  }

  def fun3(args: Int*): Int = {
    if (args.length == 0) 0
    else args.head + fun3(args.tail: _*)
  }

  // 过程定义
  def box(s: String) {
    // Look carefully: no =
    val border = "-" * s.length + "--\n"
    println("\n" + border + "|" + s + "|\n" + border)
  }

  // 或者如此定义
  def box1(s: String): Unit = {
    // Look carefully: no =
    val border = "-" * s.length + "--\n"
    println("\n" + border + "|" + s + "|\n" + border)
  }
}
